package cn.wolfcode.service.impl;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContextUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public List<Long> markReadAll(Long id) {
        return  noticeMapper.markReadAll(id);
    }

    @Override
    public void insertReadStatus(Long id,Long nid) {
        List<Long > markRead  = noticeMapper.selectWhetherRead(id);
        if (!markRead.contains(nid)) {
            noticeMapper.insertReadStatus(id,nid);
        }
    }

    @Override
    public void alterStatus(Notice notice) {
        noticeMapper.alterStatus(notice);
    }

    @Override
    public void noticeHin(NoticeQueryObject qo) {
        List<Long> longs = this.markReadAll(UserContextUtil.getUserContext().getId());
        qo.setPageSize(0);
        qo.setRead(longs);
        qo.setSeekRead(false);
        qo.setAdmin(UserContextUtil.getUserContext().isAdmin());
        //查询未读的公告
        List<Notice> list = this.query(qo).getList();
        System.out.println(list);
        //把没读的消息传进session
        for (Notice notice : list) {
            notice.setIntervalTime(DateUtil.formatBetween(new Date(),notice.getCreationTime(), BetweenFormater.Level.MINUTE));
        }
        UserContextUtil.setNoticeContext(list);
    }
}
